// pages/wantBuy/wantBuy.js
const app = getApp();
Page({
  data: {
    onReachBottomLoading: false,
    refreshed: false, // 将本属性设置为true，收起下拉刷新，可多次设置为true（即便原来已经是true了）
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    screenHeight: app.globalData.screenHeight,
    TabCur: 0,
    tabList: [{
        name: '求购',
        id: 0
      },
      {
        name: '一口价',
        id: 1
      },
      {
        name: '拍卖',
        id: 2
      }
    ],
    wantBuyList: {}, // 对象 页数为key，防止多次触发触底造成数据重复现象
    searchParams: {
      pageNum: 1,
      pageSize: 6, //默认为6
      total: 0, //总条数
      pages: 0, //总页数
      city: '', //为全国时不传值
      keyword: '', //条件模糊查询。,
      searchtype: 0
    },
    noData: true,

    secondBatchList: {},
    sebSearchParams: {
      pageNum: 1,
      pageSize: 6, //默认为6
      total: 0, //总条数
      pages: 0, //总页数
      city: '', //为全国时不传值
      keyword: '', //条件模糊查询。,
      searchtype: 0
    },
    sebNoData: true,
    secondBatchTimer: null,


    auctionList: {}, // 对象 页数为key，防止多次触发触底造成数据重复现象
    auSearchParams: {
      pageNum: 1,
      pageSize: 6, //默认为6
      total: 0, //总条数
      pages: 0, //总页数
      city: '', //为全国时不传值
      queryType: '1', //查询类型
    },
    auNoData: true,
    auctionTimer: null
  },

  /**
   * 组件的方法列表
   */
 
    goSearch() {
      switch (this.data.TabCur) {
        case 0:
          if('' != this.data.searchParams.keyword){
            this.setData({
              'searchParams.searchtype':1
            })
          }
          break;
        case 1:
          if('' != this.data.sebSearchParams.keyword){
            this.setData({
              'sebSearchParams.searchtype':1
            })
          }
          break;
      }
      this.resetQuery();
      this.goQuery();
    },
    clearQuery(){
      switch (this.data.TabCur) {
        case 0:
          this.setData({
            'searchParams.searchtype':0,
            'searchParams.keyword':''
          })
          break;
        case 1:
          this.setData({
            'sebSearchParams.searchtype':0,
            'sebSearchParams.keyword':''
          })
          break;
      }
      this.resetQuery();
      this.goQuery();
    },
    goQuery() {
      this.setData({
        'onReachBottomLoading': true
      });
      switch (this.data.TabCur) {
        case 0:
          this.goWantBuyQuery();
          break;
        case 1:
          this.goSebQuery();
          break;
        case 2:
          this.goAuQuery();
          break;
      }
    },
    // 搜索求购列表
    goWantBuyQuery() {
      let searchParams = app.deepCopy(this.data.searchParams);
      // searchParams = this.arrangeParams(searchParams);
      // searchParams.city == "" ? delete searchParams.city : '';
      // 整理完成进行搜索操作。
      app.sHttp.wantBuyList(searchParams).then(res => {
        let wantBuyList = this.data.wantBuyList;
        wantBuyList[searchParams.pageNum] = res.result.wantBuyList;
        if (0 == res.result.total) {
          this.setData({
            'noData': true,
            'onReachBottomLoading': false
          })
        } else {
          this.setData({
            'noData': false,
            'wantBuyList': wantBuyList,
            'searchParams.total': res.result.total,
            'searchParams.pages': res.result.pages,
            'onReachBottomLoading': false
          });
        }
      }, err => {
        app.error(err.msg);
      })
    },
    // 搜索一口价列表。
    goSebQuery() {
      let searchParams = app.deepCopy(this.data.sebSearchParams);
      // searchParams.city == "" ? delete searchParams.city : '';
      // 整理完成进行搜索操作。
      app.sHttp.secondBatchList(searchParams).then(res => {
        let secondBatchList = this.data.secondBatchList;
        secondBatchList[searchParams.pageNum] = res.result.secondBatchList;
        if (0 == res.result.total) {
          this.setData({
            'sebNoData': true,
            'onReachBottomLoading': false
          })
        } else {
          this.setData({
            'sebNoData': false,
            'secondBatchList': secondBatchList,
            'sebSearchParams.total': res.result.total,
            'sebSearchParams.pages': res.result.pages,
            'onReachBottomLoading': false
          });
          // this.handleTimer();
        }
      }, err => {
        app.error(err.msg);
      })

    },
    // 查询拍卖列表。
    goAuQuery() {
      let searchParams = app.deepCopy(this.data.auSearchParams);
      // 整理完成进行搜索操作。
      app.sHttp.auctionList(searchParams).then(res => {
        let auctionList = this.data.auctionList;
        // 测试数据
        // res.result.auctionList[0].endTime = '2021-10-27 00:00:00';
        // res.result.auctionList[0].status = 3;
        auctionList[searchParams.pageNum] = res.result.auctionList;
        if (0 == res.result.total) {
          this.setData({
            'auNoData': true,
            'onReachBottomLoading': false
          })
        } else {
          this.setData({
            'auNoData': false,
            'auctionList': auctionList,
            'auSearchParams.total': res.result.total,
            'auSearchParams.pages': res.result.pages,
            'onReachBottomLoading': false
          });
          this.handleAuTimer();
        }
      }, err => {
        app.error(err.msg);
      })

    },
    tabSelect(e) {
      if (e.currentTarget.dataset.id == this.data.TabCur) {
        return;
      }
      this.setData({
        TabCur: e.currentTarget.dataset.id,
        scrollLeft: (e.currentTarget.dataset.id - 1) * 60
      });
      let key = 'wantBuyList';
      switch (this.data.TabCur) {
        case 0:
          key = 'wantBuyList';
          this.InitTheSebInter(false);
          break;
        case 1:
          key = 'secondBatchList';
          this.InitTheSebInter(true);
          break;
        case 2:
          key = 'auctionList';
          this.InitTheSebInter(true);
          break;
      }
      if (Object.keys(this.data[key]).length === 0) {
        this.goSearch();
      }
    },
    // 加载位置信息
    loadLocations(type) {
      if(this.data.TabCur == 2){
        return;
      }
      let city = app.globalData.defaultCity == '全国'?'':app.globalData.defaultCity;
      if(this.data.TabCur == 1){
        if (city == this.data.sebSearchParams.city && 'jump' != type) {
          return;
        }
      }
      if(this.data.TabCur == 0){
        if (city == this.data.searchParams.city && 'jump' != type) {
          return;
        }
      }
      let key = 'searchParams.city';
      switch (this.data.TabCur) {
        case 1:
          key = 'sebSearchParams.city';
          break;
      }
      this.setData({
        [key]: '全国' == city ? '' : city
      });
      this.goSearch();
    },
    InitTheSebInter(type) {
      if (this.data.secondBatchTimer) {
        clearInterval(this.data.secondBatchTimer);
      };
      if (this.data.auctionTimer) {
        clearInterval(this.data.auctionTimer);
      };
      if (type) {
        if (Object.keys(this.data.secondBatchList).length > 0 && 1 == this.data.TabCur) {
          this.setCountDown();
        }
        if (Object.keys(this.data.auctionList).length > 0 && 2 == this.data.TabCur) {
          this.setAuCountDown();
        }
      }
    },
    // 跳转到省市选择
    toCitySelector() {
      wx.navigateTo({
        url: '/pages/StSwitchCity/StSwitchCity',
      })
    },
    infoSearchText(e) {
      let key = 'searchParams.keyword';
      switch (this.data.TabCur) {
        case 1:
          key = 'sebSearchParams.keyword';
          break;
      }
      this.setData({
        [key]: e.detail.value
      })
    },
    makePhoneCall(e) {
      if (2 != this.data.userInfo.accountStatus) {
        app.alert('您当前尚未注册，无法拨打电话');
        return;
      }
      let num = e.currentTarget.dataset.num;
      let IndexItem = e.currentTarget.dataset.idx;
      let contactMobile = "";
      if(this.data.TabCur == 0){
        let wantBuyItem = this.data.wantBuyList[num + ''][IndexItem];
        contactMobile = wantBuyItem.userMobile;
      }
      if(this.data.TabCur == 1){
        let secondBatchItem = this.data.secondBatchList[num + ''][IndexItem];
        contactMobile = secondBatchItem.userMobile;
      }
      if (undefined != contactMobile && null != contactMobile && '' != contactMobile) {
        wx.makePhoneCall({
          phoneNumber: contactMobile,
          success:function(){},
          fail:function(){}
        })
      } else {
        app.alert('未查询到车主电话');
      }
    },
    resetQuery() {
      let self = this;
      switch (this.data.TabCur) {
        case 0:
          this.setData({
            'wantBuyList': self.loveHerByOneDay(self.data.wantBuyList), // 对象 页数为key，防止多次触发触底造成数据重复现象
            'searchParams.pageNum': 1,
            'searchParams.total': 1,
            'searchParams.pages': 1
          })
          break;
        case 1:
          this.setData({
            'secondBatchList': self.loveHerByOneDay(self.data.secondBatchList), // 对象 页数为key，防止多次触发触底造成数据重复现象
            'sebSearchParams.pageNum': 1,
            'sebSearchParams.total': 1,
            'sebSearchParams.pages': 1,
          })
          break;
        case 2:
          this.setData({
            'auctionList': self.loveHerByOneDay(self.data.auctionList), // 对象 页数为key，防止多次触发触底造成数据重复现象
            'auSearchParams.pageNum': 1,
            'auSearchParams.total': 1,
            'auSearchParams.pages': 1,
          })
          break;
      }
    },
    loveHerByOneDay(her){
      if(Object.keys(her).length != 0){
        // 保留里面的 key 为 1 的数据
        let newObj = {};
        newObj[1] = her[1];
        return newObj;
      }else{
        return {};
      }
    },
    onReachBottom() {
      let key = 'searchParams';
      switch (this.data.TabCur) {
        case 1:
          key = 'sebSearchParams';
          break;
        case 2:
          key = 'auSearchParams';
          break;
      }
      if (this.data[key].pageNum == this.data[key].pages) {
        //app.alert('没有更多了哦~');
      } else {
        let self = this;
        let keypy = key + '.pageNum';
        this.setData({
          [keypy]: self.data[key].pageNum + 1
        });
        this.goQuery();
      }
    },
    previewImage(e) {
      let key = 'wantBuyList';
      switch (this.data.TabCur) {
        case 1:
          key = 'secondBatchList';
          break;
        case 1:
          key = 'auctionList';
          break;
      }
      let num = e.currentTarget.dataset.num;
      let IndexItem = e.currentTarget.dataset.idx;
      let picIndex = e.currentTarget.dataset.picidx;
      let items = this.data[key][num + ''][IndexItem];
      let picList = [];
      let picKey = 'picList';
      switch (this.data.TabCur) {
        case 1:
          picKey = 'carPicList';
          break;
      }
      items[picKey].forEach(item => {
        picList.push(item.picUrl);
      });
      wx.previewImage({
        current: picList[picIndex],
        urls: picList
      })
    },
    goSeeSeb(e) {
      wx.navigateTo({
        url: '/pages/card/secondBatch/secondBatch?sid=' + e.currentTarget.dataset.sid,
      })
    },
    // 计算倒计时。
    handleTimer() {
      var that = this
      var secondBatchList = that.data.secondBatchList;
      for (const key in secondBatchList) {
        if (Object.hasOwnProperty.call(secondBatchList, key)) {
          const element = secondBatchList[key];
          element.forEach(element => {
            element.time = that.queryTime(element.secondBatchTime);
          });
        }
      }
      this.setData({
        'secondBatchList': secondBatchList
      });
      this.setCountDown();
    },
    setCountDown() {
      if (this.data.secondBatchTimer) {
        clearInterval(this.data.secondBatchTimer);
      };
      let self = this;
      let secondBatchTimer = setInterval(() => {
        console.log('我是老大');
        let time = 1000;
        let {
          secondBatchList
        } = self.data;
        for (const key in secondBatchList) {
          if (Object.hasOwnProperty.call(secondBatchList, key)) {
            const element = secondBatchList[key];
            element.map((v, i) => {
              if (v.time <= 0) {
                v.time = 0;
              }
              let formatTime = self.getFormat(v.time);
              v.time -= time;
              v.countDown = `${formatTime.hh}:${formatTime.mm}:${formatTime.ss}`;
              return v;
            })
          }
        }
        self.setData({
          'secondBatchList': secondBatchList
        });
      }, 1000);
      this.setData({
        'secondBatchTimer': secondBatchTimer
      })
    },
    handleAuTimer() {
      var that = this
      var auctionList = that.data.auctionList;
      for (const key in auctionList) {
        if (Object.hasOwnProperty.call(auctionList, key)) {
          const element = auctionList[key];
          element.forEach(element => {
            element.time = that.queryTime(element.endTime);
          });
        }
      }
      this.setData({
        'auctionList': auctionList
      });
      this.setAuCountDown();
    },
    // 设置一个拍卖的倒计时。
    setAuCountDown() {
      if (this.data.auctionTimer) {
        clearInterval(this.data.auctionTimer);
      };
      let self = this;
      let auctionTimer = setInterval(() => {
        console.log('我是老二');
        let time = 1000;
        let {
          auctionList
        } = self.data;
        for (const key in auctionList) {
          if (Object.hasOwnProperty.call(auctionList, key)) {
            const element = auctionList[key];
            element.map((v, i) => {
              if (3 == v.status) {
                if (v.time <= 0) {
                  v.time = 0;
                }
                let formatTime = self.getFormat(v.time);
                v.time -= time;
                v.countDownHH = formatTime.hh;
                v.countDownMM = formatTime.mm;
                v.countDownSS = formatTime.ss;
              }
              return v;
            })
          }
        }
        self.setData({
          'auctionList': auctionList
        });
      }, 1000);
      this.setData({
        'auctionTimer': auctionTimer
      })
    },
    getFormat(msec) {
      let ss = parseInt(msec / 1000);
      let ms = parseInt(msec % 1000);
      let mm = 0;
      let hh = 0;
      if (ss > 60) {
        mm = parseInt(ss / 60);
        ss = parseInt(ss % 60);
        if (mm > 60) {
          hh = parseInt(mm / 60);
          mm = parseInt(mm % 60);
        }
      }
      ss = ss > 9 ? ss : `0${ss}`;
      mm = mm > 9 ? mm : `0${mm}`;
      hh = hh > 9 ? hh : `0${hh}`;
      return {
        ss,
        mm,
        hh
      };
    },
    queryTime(pintime) {
      var start_date = new Date();
      var end_date = new Date(pintime.replace(/-/g, "/"));
      var days = end_date.getTime() - start_date.getTime();
      console.log("获取到时间差" + days)
      return days;
    },
    switchType(e) {
      let type = e.currentTarget.dataset.type;
      let _this = this;
      this.setData({
        'auSearchParams.queryType': type
      }, (res) => {
        if (_this.data.auctionTimer) {
          clearInterval(_this.data.auctionTimer);
        }
        _this.goSearch();
      })
    },
    goSeeAub(e) {
      wx.navigateTo({
        url: '/pages/card/auction/auction?aid=' + e.currentTarget.dataset.aid,
      })
    },
    pullDownRefresh(){
      this.lifeInit();
      this.goSearch();
      let self = this;
      setTimeout(() => {
        self.setData({
          'refreshed': true
        })
      }, 1000);
    },
    // 真正的初始化页面。
    lifeInit(){
      // 加载一个方法。来装载Token以及其他参数。
      this.InitUserStatus();
      app.globalData.wantBuyComponentLoadTime = new Date();
    },
    async InitUserStatus(){
      await app.checkToken();
      let accountStatus = app.accountStatus;
      // 回填权限列表。
      let userInfo = app.globalData.userInfo;
      if (undefined != userInfo.roleList && null != userInfo.roleList) {
        this.setData({
          roleList: userInfo.roleList
        });
      }
      this.setData({
        accountStatus: accountStatus,
        userInfo:userInfo
      });
      if(this.getTabBar()){
        this.getTabBar().setData({
          roleList:userInfo.roleList,
          accountStatus:accountStatus,
          userInfo:userInfo,
          remindList:userInfo.remindList
        })
      }
      this.loadDealerInfo();
      this.loadMsgUnreadStat();
      this.loadLocations('jump');
    },
    loadMsgUnreadStat(){
      app.sHttp.msgUnreadStat().then(res =>{
        this.setData({
          'msgNumber': res.result
        });
        if(this.getTabBar()){
          this.getTabBar().setData({
            'msgNumber': res.result
          })
        }
      },err=>{
      })
    },  // 加载下车商的信息。
    loadDealerInfo(){
      if(Object.keys(app.globalData.dealerInfo).length === 0){
        app.sHttp.dealerInfo().then(res =>{
          if(res.result.city == '市辖区'){
            res.result.city = res.result.province;
          }
          app.globalData.dealerRegion = [res.result.province, res.result.city , res.result.district];
          app.globalData.dealerInfo = res.result;
          // 并且把地址填充到
          // app.globalData.defaultCity = res.result.city || '全国';
        },err=>{
        })
      }
    },
    onShow() {
      if(app.globalData.reloadWantBuy && this.data.TabCur == 0){
        app.globalData.reloadWantBuy = false;
        this.lifeInit();
        return;
      }
      // 是否需要请求
      if(null == app.globalData.wantBuyComponentLoadTime || app.needReload(app.globalData.wantBuyComponentLoadTime)){
        this.lifeInit();
      }else{
        this.loadLocations();
        this.InitTheSebInter(true);
      }
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          selected: 1
        })
      }
    },
    onHide(){
      this.InitTheSebInter(false);
    },
})